<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
use think\Config;
class Tong extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
//        extract(input());
//        if($user_id != 0){
//            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//            if($auth == 112){
//                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
//                exit;
//            }elseif($auth == 110){
//                echo json_encode(['status' => 302, 'msg' => $this->frost]);
//                exit;
//            }elseif($auth == 1103){
//                echo json_encode(['status' => 303, 'msg' => $this->del]);
//                exit;
//            }
//        }

    }

    /**
     * 我的统购购买订单！！！！！！
     */
    public function myTongOrder()
    {
        extract(input());
        $today = date('Y-m-d');
        $can = $this->getSonByUser($user_id);
        if($can['status'] != 200){
            return json($can);
        }
        $sondata = $can['msg'];
        $school = Db::table('up_school')
            ->where('school_id',$sondata['uson_school'])
            ->field('school_name,school_erp')
            ->find();
        $school['year'] = $sondata['uson_year'];
        $where = [
            'ts_school_erp' => $school['school_erp']
        ];
        $canshow = Db::table('up_self_order')
            ->where('order_user_son_id',$sondata['uson_id'])
            ->where('order_contract',3)
            ->where('is_pay',1)
            ->column('order_ts_id');
        if($canshow){
            $where['ts_id'] = ['not in',$canshow];
        }
        $data = Db::table('up_tg_school')
            ->where($where)
            ->where('ts_status',1)
            ->where('ts_begin','<=',$today)
            ->where('ts_end','>=',$today)
            ->where('ts_year',$sondata['uson_year'])
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if(!$v['ts_student'] || strstr(',' . $sondata['uson_username'] . ',',$v['ts_student'])){
                    $data[$k]['lists'] = Db::table('up_tg_school_list tsl')
                        ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
                        ->where('tsl_ts_id',$v['ts_id'])
                        ->where('tsl_del',1)
                        ->where('sg_sex','in',"{$sondata['user_gender']},3")
                        ->group('tsl_type')
                        ->field('tsl_id,tsl_ts_id,tsl_type,sum(tsl_num) num')
                        ->select();
                    $newMoney = Db::table('up_tg_school_list tsl')
                        ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
                        ->where('tsl_ts_id',$v['ts_id'])
                        ->where('tsl_del',1)
                        ->where('sg_sex','in',"{$sondata['user_gender']},3")
                        ->field('tsl_num*tsl_price one_all_price')
                        ->select();
                    $one_all_price = array_column($newMoney,'one_all_price');
                    $data[$k]['ts_money'] = array_sum($one_all_price);
                }else{
                    unset($data[$k]);
                }
            }
        }
        return json(['status' => 200,'school' => $school,'msg' => $data]);
    }
    /**
     * 我的统购购买订单详情！！！！！！
     */
    public function myTongOrderInfo()
    {
        extract(input());
        $today = date('Y-m-d');
        $can = $this->getSonByUser($user_id);
        if($can['status'] != 200){
            return json($can);
        }
        $sondata = $can['msg'];
        $data = Db::table('up_tg_school_list tsl')
            ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
            ->where('tsl_ts_id',$ts_id)
            ->where('sg_sex','in',"{$sondata['user_gender']},3")
            ->where('tsl_del',1)
            ->group('tsl_type')
            ->field('tsl_id,tsl_ts_id,tsl_type,sum(tsl_num) num,sum(tsl_price) price')
            ->select();
        foreach ($data as $k => $v){
            $data[$k]['lists'] = Db::table('up_tg_school_list tsl')
                ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
                ->join('up_goods g','sg.sg_good_coding=g.good_coding','LEFT')
                ->where('tsl_ts_id',$ts_id)
                ->where('sg_sex','in',"{$sondata['user_gender']},3")
                ->where('tsl_type',$v['tsl_type'])
                ->where('tsl_del',1)
                ->field('good_name,good_thumb,tsl_num,tsl_price,tsl_num*tsl_price one_all_price')
                ->select();
            $one_all_price = array_column($data[$k]['lists'],'one_all_price');
            $data[$k]['price'] = array_sum($one_all_price);
        }
        //----------------
        $tgInfo = Db::table('up_tg_school')
            ->where('ts_id',$ts_id)
            ->find();
        $newMoney = Db::table('up_tg_school_list tsl')
            ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
            ->where('tsl_ts_id',$ts_id)
            ->where('tsl_del',1)
            ->where('sg_sex','in',"{$sondata['user_gender']},3")
            ->field('tsl_num*tsl_price one_all_price')
            ->select();
        $one_all_price = array_column($newMoney,'one_all_price');
        $tgInfo['ts_money'] = array_sum($one_all_price);
        if(!isset($address_id) || !$address_id){
            $address_id = '';
        }
        $address = $this->myAddressInfo($user_id,$address_id);
        if(empty($address)){
            $address = '';
        }
        return json(['status' => 200,'msg' => $data,'sondata' => $sondata,'tgInfo' => $tgInfo,'address' => $address]);
    }
    /**
     * 购买
     * ts_id：
     * size：1_150|2_150
     * $pay_type:1
     * $address_id:1
     */
    public function payTongOrder()
    {
        extract(input());
//        $address_id = 1;
//        $remark = '';
//        $pay_type = 1;
//        $ts_id = '11';
//        $user_id = 1;
//        $size = '1_100|2_100|3_100|4_100|5_100';
//        return json(['status'=>0,'msg'=>$type.$address_id.$remark.$pay_type.$ids.$user_id]);
        if($pay_type == 3){
            return json(['status'=>0,'msg'=>'银联支付暂未开放，敬请期待~']);
        }
        $today = date('Y-m-d H:i:s');
        $address = $this->myAddressInfo($user_id,$address_id);
        if(!$address['sheng'] || !$address['shi'] || !$address['qu'] || !$address['address_detail']){
            return json(['status'=>0,'msg'=>'地址不能为空，请重新选择或新建~']);
        }
        $number = date('YmdHis') . rand(1000000,9999999);
        $zhi_xia = [
            '北京','天津','重庆','上海'
        ];
        $order_address2 = $address['sheng'] . '|||' . $address['shi'] . '|||' . $address['qu'] . '|||' . $address['address_detail'];
        if(in_array($address['sheng'],$zhi_xia)){
            $address['sheng'] = '';
        }
        $order = [
            'user_id' => $user_id,
            'order_no' => $number,
            'name' => $address['address_name'],
            'mobile' => $address['address_phone'],
            'address' => $address['sheng'] . $address['shi'] . $address['qu'] . $address['address_detail'],
            'order_address2' => $order_address2,
            'remark' => $remark,
            'pay_type' => $pay_type,
            'pay_time' => $today,
            'created_at' => $today,
            'updated_at' => $today,
        ];
        if(empty($order['address'])){
            return json(['status'=>0,'msg'=>'地址不能为空，请重新选择或新建~']);
        }
        Db::startTrans();
        try{
            $tg_data = Db::table('up_tg_school')->where('ts_id',$ts_id)->find();
            $can = $this->getSonByUser($user_id);
            if($can['status'] != 200){
                return json($can);
            }
            $sondata = $can['msg'];
            $user_son_id = $sondata['uson_id'];
//------------------------------------------------------------------------------
            $havepay = Db::table('up_self_order')
                ->where('order_user_son_id',$user_son_id)
                ->where('order_contract',3)
                ->where('order_ts_id',$ts_id)
                ->where('is_pay',1)
                ->find();
            if($havepay){
                return json(['status'=>0,'msg'=>'此学生的此统购订单已支付过了~']);
            }
            $type_size = [];
            $sizes = explode('|',trim($size,'|'));
            if(empty($sizes)){
                return json(['status'=>0,'msg'=>'尺码选择有误~']);
            }
            foreach ($sizes as $k=>$v) {
                $v = explode('_', $v);
                $type_size[$v[0]] = $v[1];
            }
            Db::table('up_self_order')
                ->where('order_user_son_id',$user_son_id)
                ->where('order_contract',3)
                ->where('order_ts_id',$ts_id)
                ->delete();
            Db::table('up_self_order_detail')
                ->where('detail_user_son_id',$user_son_id)
                ->where('tg_id',$ts_id)
                ->delete();
            //------------------------------------------------------------------------------
            $order['order_ts_id'] = $ts_id;
            $order['order_contract'] = 3;
            $order['order_user_son_id'] = $user_son_id;
            $order['order_son_grade'] = $sondata['uson_grade'];
            $order['order_school'] = Db::table('up_school')->where('school_id',$sondata['uson_school'])->value('school_erp');

            $order['total_price'] = $tg_data['ts_money'] + $tg_data['ts_post'];
            $order['express_original_price'] = $tg_data['ts_post'];
            $order['all_goods_price'] = $tg_data['ts_money'];
            $order_id = Db::table('up_self_order')->insertGetId($order);
            //为了后台的商品名字和总数量
            //年份和交期
            $time = time();
            $days = $tg_data['ts_done'];
            $days = (int)$days;
            $days_after = date("Ymd",($time + 3600*$days*24));
            $order_erp_year = $tg_data['ts_year'];
            $order_erp_done = $days_after;
            //---------------------
            $sgs = Db::table('up_tg_school_list tsl')
                ->join('up_school_good sg','tsl.tsl_sg_id=sg.sg_id','LEFT')
                ->join('up_goods g','sg.sg_good_coding=g.good_coding','LEFT')
                ->where('tsl_ts_id',$ts_id)
                ->where('sg_sex','in',"{$sondata['user_gender']},3")
                ->where('tsl_del',1)
                ->field('good_id,good_name,good_color,sg.good_price,sg_good_coding,sg_sign,tsl_id,tsl_type,tsl_price,tsl_num')
                ->select();
            $num = 0;
            $first_good_name = '';
            if(empty($sgs)){
                Db::rollback();
                return json(['status'=>0,'msg'=>'统购订单数据有误~']);
            }
            $tgFive = [
                1 => '夏季套装' ,
                2 => '秋季套装' ,
                3 => '礼服套装' ,
                4 => '冬季套装' ,
                5 => '西服套装'
            ];
            $sexAllMoney = 0;
            foreach ($sgs as $k=>$v){
                //>>>>>>>>>>>>>>>>>>>获取唯一编码start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                $size_code = Db::table('up_good_spec')
                    ->where('spec_good_coding', $v['sg_good_coding'])
                    ->where('spec_size', $type_size[$v['tsl_type']])
                    ->value('spec_size_two');
                if(empty($size_code)){
                    Db::rollback();
                    return json(['status'=>0,'msg'=>$tgFive[$v['tsl_type']] . '尺码有误，请刷新重试，或重新选择尺码~']);
                }
                $unique_code = $v['sg_good_coding'] . $size_code;
                if ($v['sg_sign']) {
                    $unique_code .= $v['sg_sign'];
                }
                $pay_year = $tg_data['ts_year'];
                //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<获取唯一编码end<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                //为了后台的商品名字和总数量
                $num += $v['tsl_num'];
                if($k == 0){
                    $first_good_name = $v['good_name'];
                }
                //
                $sexAllMoney = $sexAllMoney + ($v['tsl_price'] * $v['tsl_num']);
                $detail = [
                    'order_id' => $order_id,
                    'detail_user_son_id' => $user_son_id,
                    'goods_id' => $v['good_id'],
                    'goods_coding_unique' => $unique_code,
                    'num' => $v['tsl_num'],
                    'unit_price' => $v['tsl_price'],
                    'goods_info' => $v['good_color'] . '/' . $type_size[$v['tsl_type']],
                    'attr_id' => $type_size[$v['tsl_type']],
                    'created_at' => $today,
                    'updated_at' => $today,
                    'pay_year' => $pay_year,
                    'tg_type' => $v['tsl_type'],
                    'tg_tsl_id' => $v['tsl_id'],
                    'tg_id' => $ts_id
                ];
                Db::table('up_self_order_detail')->insertGetId($detail);
            }
            //为了后台的商品名字和总数量
            Db::table('up_self_order')->where('order_id',$order_id)->update([
                'first_good_name' => $first_good_name,
                'all_good_nums' => $num,
                'order_erp_year' => $order_erp_year,
                'order_erp_done' => $order_erp_done,
                'total_price' => $sexAllMoney + $tg_data['ts_post'],
                'all_goods_price' => $sexAllMoney,
            ]);
            Db::commit();
            $order['total_price'] = $sexAllMoney + $tg_data['ts_post'];
//            return json(['status'=>200,'msg'=>'ok~']);
//--------------------支付方式------------------
            if($pay_type == 1){
                $payorder = array();
                $payorder['body'] = '派逊商城'; // 描述
                $payorder['total_fee'] = $order['total_price']*100; // 订单金额
                $payorder['out_trade_no'] = $number; // 订单号
                $payorder['product_id'] = ''; // 产品ID
                $payorder['trade_type'] = 'APP'; // 类型
                $mww_weixinpay =  new \app\api\controller\Weixin();
                $respont = $mww_weixinpay->WeChatPayReady($payorder);
                return json(['status'=>200,'msg'=>$respont,'order_id'=>$order_id,'pay_type'=>$pay_type,'total_price'=>$order['total_price']]);
            }else{
                $mww_alipay =  new \app\api\controller\Ali();
                $respont = $mww_alipay->getParam($number, $order['total_price'], '派逊商城', '派逊商城');
                $respont['order_id'] = $order_id;
                $respont['pay_type'] = $pay_type;
                $respont['total_price'] = $order['total_price'];
                return json($respont);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'生成订单失败，请刷新重试~']);
        }
    }
    //------------------------------------------我的--------------------------------------------------------------
    /**
     * 我的某一个统购订单详情
     */
    public function myOrderInfo()
    {
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $where = [
            'od.order_id' => $order_id
        ];
        $details = Db::table('up_self_order_detail od')
            ->where($where)
            ->group('tg_type')
            ->field('tg_type,sum(num) num')
            ->select();
        return json(['status'=>200,'msg'=>$order,'goods'=>$details]);
    }
    /**
     * 我的某一个统购订单详情——套装列表
     */
    public function myOrderTypes()
    {
        extract(input());
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('order_id,is_sale')
            ->find();
        $where = [
            'od.order_id' => $order_id
        ];
        if(isset($tui) && $tui == 1){
            $where['od.refund_status'] = 0; //未售后的，售后结束的不能再次售后
        }
        $field = 'tg_type,attr_id,th_status,refund_status,sum(num) num,sum(unit_price) price,detail_express,detail_express_no';
        $field .= ',tui.status,tui.is_send,tui.merchant_remark,tui.merchant_express,tui.merchant_express_no,tui.express_no';
        $field .= ',tui.erp_new_size,tui.remark,tui.pic_list';
        $data = Db::table('up_self_order_detail od')
            ->join('up_self_order_tui tui','od.detail_id=tui.order_detail_id','LEFT')
            ->where($where)
            ->group('tg_type')
            ->field($field)
            ->select();
        foreach ($data as $k => $v){
            if($v['pic_list']){
                $data[$k]['pic_list'] = explode(',',$v['pic_list']);
            }
            $data[$k]['lists'] = Db::table('up_self_order_detail od')
                ->join('up_goods g','od.goods_id=g.good_id','LEFT')
                ->where($where)
                ->where('tg_type',$v['tg_type'])
                ->field('good_name,good_thumb,num,unit_price,num*unit_price one_all_price')
                ->select();
            $one_all_price = array_column($data[$k]['lists'],'one_all_price');
            $data[$k]['price'] = array_sum($one_all_price);
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 申请售后：只有已发货后的才可以
     * order_id：订单id
     * tg_type：类型id
     * $newsize：新尺码
     * $remark：备注
     * $pic_list：图片
     */
    public function afterSaleTongOrder()
    {
        extract(input());
//        $detail_ids='445';$order_id=464;$type=1;$newsizes='120';$user_id=1;$remark='换货';$express='顺丰';$express_no='112233';
        $today = date('Y-m-d H:i:s');
        $orderFor3 = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('is_send,is_pay,is_sale,order_user_son_id,order_erp_year,order_ts_id')
            ->find();
        $is_send = $orderFor3['is_send'];
        if ($is_send < 2 || $orderFor3['is_pay'] != 1) {
            return json(['status' => 0, 'msg' => '只有已收货订单才可以申请售后']);
        }
        if ($orderFor3['is_sale'] != 0) {
            return json(['status' => 0, 'msg' => '已过了售后时间']);
        }
        if (!$newsize || $newsize <= 0) {
            return json(['status' => 0, 'msg' => '请选择要换货的尺码']);
        }
        $tui_user_son_id = $orderFor3['order_user_son_id'];
        Db::startTrans();
        try {
            $erp_wl_no = 'app' . time() . rand(10, 99) . $tui_user_son_id;
            $days = Db::table('up_tg_school')->where('ts_id',$orderFor3['order_ts_id'])->value('ts_done');
            $days = (int)$days;
            $details = Db::table('up_self_order_detail od')
                ->join('up_goods g','od.goods_id=g.good_id','LEFT')
                ->where('order_id',$order_id)
                ->where('tg_type',$tg_type)
                ->field('detail_id,attr_id,goods_id,pay_year,tg_tsl_id,good_coding,od.num')
                ->select();
            foreach ($details as $k => $v) {
                //1、入售后表：
                $number = time() . rand(100000, 999999) . $k;
                $tui = [
                    'user_id' => $user_id,
                    'tui_type' => 3,
                    'tui_user_son_id' => $tui_user_son_id,
                    'order_id' => $order_id,
                    'order_detail_id' => $v['detail_id'],
                    'order_no' => $number,
                    'order_erp_wl_no' => $erp_wl_no,
                    'type' => 1,//1换货 2退款
                    'refund_price' => 0,
                    'refund_num' => $v['num'],
                    'remark' => $remark,
                    'pic_list' => $pic_list,
                    'tui_tg_type' => $tg_type,
                    'express' => '',
                    'express_no' => '',
                    'created_at' => $today
                ];
                $size_code = Db::table('up_good_spec')
                    ->where('spec_good_coding', $v['good_coding'])
                    ->where('spec_size', $newsize)
                    ->value('spec_size_two');
                if(empty($size_code)){
                    Db::rollback();
                    return json(['status'=>0,'msg'=>'尺码有误，重新选择尺码~']);
                }
                $unique_code = $v['good_coding'] . $size_code;
                $sg_id = Db::table('up_tg_school_list')
                    ->where('tsl_id', $v['tg_tsl_id'])
                    ->value('tsl_sg_id');
                if ($sg_id) {
                    $sg_sign = Db::table('up_school_good')
                        ->where('sg_id', $sg_id)
                        ->value('sg_sign');
                    if ($sg_sign) {
                        $unique_code .= $sg_sign;
                    }
                }
                $tui['erp_new_size'] = $newsize;
                $tui['erp_huan_uninumber'] = $unique_code;
                //年份和交期
                $time = time();
                $days_after = date("Ymd",($time + 3600*$days*24));
                $tui['erp_year'] = $v['pay_year'];
                $tui['erp_done'] = $days_after;
                Db::table('up_self_order_tui')->insert($tui);
            }
            //2、改详情表
            Db::table('up_self_order_detail')
                ->where('order_id',$order_id)
                ->where('tg_type',$tg_type)
                ->update([
                'refund_status' => 1,
                'th_status' => 1,
            ]);
            //3、改order表售后状态
            Db::table('up_self_order')->where('order_id', $order_id)->update([
                'sale_status' => 2,
                'tui_status' => 0,
            ]);
            Db::commit();
            $title = '换货通知';
            $content = '发起换货后，我们将进行核实，并与您联系';
            allInNotice($title,$content,3,$user_id,$order_id,3);
            try{
                $this->Jpush(1, $user_id, '发起售后通知', ['n_id' => $order_id,'type' => 3,'n_type' => 3]);
            }catch(\Exception $e){

            }
            return json(['status' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }
    /**
     * 用户售后回寄
     * @return \think\response\Json
     */
    public function userHuanPost()
    {
        extract(input());
        if(!$express || !$express_no){
            return json(['status' => 0, 'msg' => '快递公司和快递单号不能为空！']);
        }
        $res = Db::table('up_self_order_tui')
            ->where('order_id',$order_id)
            ->where('tui_tg_type',$tg_type)
            ->update([
                'express' => $express,
                'express_no' => $express_no,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功，请您耐心等待~']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }
    /**
     * 查看售后已发货后的套装详情
     * @return \think\response\Json
     */
    public function getTongHuanInfo()
    {
        extract(input());
        //
        $order = Db::table('up_self_order')->where('order_id', $order_id)
            ->field('name,mobile,address')
            ->find();
        $after_sale = Db::table('up_self_order_tui')
            ->where('order_id',$order_id)
            ->where('tui_tg_type',$tg_type)
            ->field('is_send,tui_user_get,order_erp_wl_no,merchant_express,merchant_express_no,created_at')
            ->find();
        return json(['status' => 200, 'msg' =>$order, 'after_sale' =>$after_sale]);
    }
    /**
     * 确认收到货
     * @return \think\response\Json
     */
    public function receiptTongSaleOrder()
    {
        extract(input());
        $res = Db::table('up_self_order_tui')
            ->where('order_id',$order_id)
            ->where('tui_tg_type',$tg_type)
            ->update([
                'tui_user_get' => 2,
                'tui_sure_get_time' => date('Y-m-d H:i:s'),
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功!']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败，请刷新重试']);
        }
    }
    /**
     * 物流
     */
    public function wuliuInfo()
    {
        extract(input());
//        $wldata = [];
//        if($express_no){
//            $wldata = orderWuLiu($express_no);
//            if($wldata['status'] == 200){
//                $wldata['time'] = $wldata['msg'][0]['time'];
//                $wldata['msg'] = $wldata['msg'][0]['context'];
//            }
//        }
        $wldata = orderWuLiu($express_no);
        if($wldata['status'] != 200){
            $wldata['msg'] = [];
        }
        return json(['status'=>200,'msg'=>$wldata]);
    }
}